package com.anlu.thread.ta1;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @program: Thread-learning
 * @description: 自定义实现一个锁
 * @author: Mr.Wang
 * @create: 2019-01-30 14:41
 **/
public class MyLock  implements Lock {

    private boolean isLocked = false;

    private Thread lockBy = null;

    private int lockCount = 0;


    @Override
    public synchronized void lock() {
        //获取当前你的线程
        Thread currentThread=Thread.currentThread();

        while (isLocked && currentThread!=lockBy){
            try {
                wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }

        isLocked = true;
        lockBy= currentThread;
        lockCount++;//1,2,3,4
        System.out.println("当前线程的引用计数："+lockCount);


    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public synchronized void unlock() {
            if(lockBy == Thread.currentThread()){
                lockCount--;
                if(lockCount==0){
                    notify();
                    isLocked=false;
                }
            }
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
